package com.csjbot.blackgaga.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.csjbot.blackgaga.core.RobotManager;
import com.csjbot.blackgaga.global.Constants;
import com.csjbot.blackgaga.model.tcp.factory.ServerFactory;
import com.csjbot.blackgaga.model.tcp.proxy.SpeakProxy;
import com.csjbot.blackgaga.model.tcp.tts.ISpeak;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.UpdateApkManagerUtil;
import com.csjbot.coshandler.global.CmdConstants;
import com.csjbot.coshandler.listener.OnHeadTouchListener;
import com.csjbot.coshandler.listener.OnInitListener;
import com.csjbot.coshandler.listener.OnWakeupListener;
import com.csjbot.coshandler.log.CsjlogProxy;

/**
 * HomeService,主要作用:
 * 负责与底层通信的连接
 * 接受底层返回的数据分发处理
 */
public class HomeService extends BaseService {

    /* 启动Activity标识 */
    public static final int START_ACTIVITY = 10;

    public static final int LINUX_CONNECTED = 0;
    public static final int LINUX_DISCONNECT = 1;


    public static boolean IS_SWITCH_LANGUAGE;

    /* 广播接收者 */
    private HomeBroadcast mHomeBroadcast;

    /* Handle消息处理 */
    private Handler mHandle = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case START_ACTIVITY:/* 启动指定的Activity */
                    startActivity(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 根据className启动对应的activity
     *
     * @param className
     */
    private void startActivity(String className) {
        BlackgagaLogger.error("chenqi 是获取到了什么className" + className);
        Class<?> c = null;
        try {
            c = Class.forName(className);
        } catch (ClassNotFoundException ignored) {
        }
        if (c != null) {
            startActivity(new Intent(this, c).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }

    public HomeService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        CsjlogProxy.getInstance().debug("class:HomeService method:onCreate");
        /* 初始化机器人管理类 */
        initRobot();
        /* 注册广播接收器 */
        regBroadcast();
        //打开远程更新
        new UpdateApkManagerUtil(getApplicationContext(), false).checkUpdateInfo();

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        CsjlogProxy.getInstance().debug("class:HomeService method:onStartCommand");
        if(IS_SWITCH_LANGUAGE){
            switchLanguage();
            IS_SWITCH_LANGUAGE = false;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void switchLanguage(){
        // 切换语音识别语言
        switch (Constants.Language.CURRENT_LANGUAGE) {
            case Constants.Language.CHINESE:
                CsjlogProxy.getInstance().info("切换到中文语言识别环境");
                ServerFactory.getSpeechInstance().setLanguage(CmdConstants.LanguageType.ZH_CH);
                break;
            case Constants.Language.ENGELISH:
                CsjlogProxy.getInstance().info("切换到英文语言识别环境");
                ServerFactory.getSpeechInstance().setLanguage(CmdConstants.LanguageType.EN_US);
                break;
            default:
                break;
        }
    }

    /**
     * 初始化机器人功能
     */
    private void initRobot() {
        /* 初始化语音合成功能 */
        SpeakProxy.getInstance().initSpeak(this);
        /* 获取机器人管理类的实例 */
        RobotManager robotManager = RobotManager.getInstance();
        /* 初始化监听 */
        robotManager.addListener(new OnInitListener() {
            @Override
            public void success() {
                mHandle.post(() -> {
                    sendBroadcast(LINUX_CONNECTED);
                });
                CsjlogProxy.getInstance().debug("class:HomeService message:linux success");

                /* 唤醒机器人 */
                ServerFactory.getSpeechInstance().openMicro();

                switchLanguage();

                ServerFactory.getConfigInstance().setMicroVolume(5);

                /* 开启语音多次识别 */
                ServerFactory.getSpeechInstance().startIsr();

                robotManager.setConnectState(true);
            }

            @Override
            public void faild() {
                robotManager.setConnectState(false);
            }

            @Override
            public void timeout() {
                robotManager.setConnectState(false);
            }

            @Override
            public void disconnect() {
                robotManager.setConnectState(false);
                CsjlogProxy.getInstance().debug("class:HomeService message:linux disconnect");
            }
        });

        /**
         * 唤醒通知
         */
        robotManager.addListener(new OnWakeupListener() {
            @Override
            public void response() {
                sendWakeupBroadcast();
                CsjlogProxy.getInstance().debug("class:HomeService message:wakeup");
                ISpeak speak = ServerFactory.getSpeakInstance();
                if(speak.isSpeaking()){
                    speak.stopSpeaking();
                }
            }
        });

        robotManager.addListener(new OnHeadTouchListener() {
            @Override
            public void response() {
                ServerFactory.getSpeakInstance().startSpeaking("不要摸人家的头啦!",null);
            }
        });

        /* 连接底层通信 */
        robotManager.connect(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CsjlogProxy.getInstance().debug("class:service method:onDestroy");
        RobotManager.getInstance().disconnect(this);
        unregBroadcast();
    }

    /**
     * 注册广播
     */
    private void regBroadcast() {
        mHomeBroadcast = new HomeBroadcast(mHandle);
        IntentFilter filter = new IntentFilter();
        filter.addAction(HomeBroadcast.ACTION_NAME);
        registerReceiver(mHomeBroadcast, filter);
    }

    /**
     * 取消广播
     */
    private void unregBroadcast() {
        unregisterReceiver(mHomeBroadcast);
    }

    /**
     * 广播接收者
     */
    public static class HomeBroadcast extends BroadcastReceiver {

        public static final String ACTION_NAME = HomeBroadcast.class.getSimpleName();
        public static final String TYPE = "TYPE";
        public static final String VALUE = "VALUE";

        private Handler mHandle;

        public HomeBroadcast(Handler handler) {
            this.mHandle = handler;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME)) {
                Bundle bundle = intent.getExtras();
                int type = bundle.getInt(TYPE);
                String value = bundle.getString(VALUE);
                mHandle.obtainMessage(type, value).sendToTarget();
            }
        }
    }

    public void sendBroadcast(int state) {
        Intent intent = new Intent();
        intent.setAction(Constants.CONNECT_LINUX_BROADCAST);
        intent.putExtra(Constants.LINUX_CONNECT_STATE, state);
        sendBroadcast(intent);
    }

    public void sendWakeupBroadcast(){
        Intent intent = new Intent();
        intent.setAction(Constants.WAKE_UP);
        sendBroadcast(intent);
    }
}
